package com.my.goodsmanage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.goodsmanage.entity.*;
import com.my.goodsmanage.enums.ThingEnum;
import com.my.goodsmanage.service.ThingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 徐佳辉
 * @date 2020/10/7 14:40
 */
@RestController
@RequestMapping("/thing")
@Slf4j
public class ThingController {

    @Autowired
    private ThingService thingService;


    /**
     * 添加事件
     *
     * @param session
     * @param thing
     * @return
     */
    @PostMapping("/insert")
    public R insert(HttpSession session, String thing) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return R.error("未登录");
        }

        QueryWrapper<Thing> wrapper = new QueryWrapper<>();
        wrapper.eq("thing", thing);
        wrapper.eq("user_id", user.getUserId());
        Thing one = thingService.getOne(wrapper);
        if (one != null) {
            return R.error("事件重复，请添加其他事件");
        }

        Thing thing1 = new Thing();
        thing1.setUserId(user.getUserId());
        thing1.setThing(thing);
        thing1.setCreateTime(new Date());
        thing1.setState(ThingEnum.NOT_FINISH.getCode());
        boolean save = thingService.save(thing1);
        int thingId = thing1.getThingId();
        log.info("thingId:[{}]", thingId);
        if (save) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }

    }

    /**
     * 根据thingId查询thing
     *
     * @param thingId
     * @return
     */
    @GetMapping("/get/{thingId}")
    public R getThing(@PathVariable int thingId) {


        QueryWrapper<Thing> wrapper = new QueryWrapper<>();
        wrapper.eq("thing_id", thingId);
        Thing one = thingService.getOne(wrapper);
        return R.success(one);
    }

    /**
     * 更新事件
     *
     * @param thing
     * @return
     */
    @PostMapping("/edit")
    public R edit(Thing thing) {
        log.info("Thing:{}", thing);
        Thing byId = thingService.getById(thing.getThingId());
        log.info("ThingbyId:{}", byId);
        byId.setThing(thing.getThing());
        byId.setState(ThingEnum.NOT_FINISH.getCode());
        byId.setCreateTime(new Date());
        boolean b = thingService.updateById(byId);
        if (b) {
            return R.success("更新成功");
        } else {
            return R.error("更新失败");
        }
    }

    /**
     * 根据thingid删除
     *
     * @param thingId
     * @return
     */
    @PostMapping("/delete/{thingId}")
    public R deleteById(@PathVariable int thingId) {
        boolean removeById = thingService.removeById(thingId);
        if (removeById) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }


    /**
     * 分页数据
     * code 0 为成功
     *
     * @return
     */
    @PostMapping("/page")
    public PageR page(@RequestParam int page, @RequestParam int limit, HttpSession session, String name) {
        User user = (User) session.getAttribute("user");
        log.info("page:[{}],size:[{}]", page, limit);
        PageR pageR = new PageR();


        Page<Thing> thingPage = new Page<>(page, limit);
        thingService.pageListCondition(thingPage, user.getUserId(), name);

        log.info("pagegoods:[{}],size:[{}],total:[{}]", thingPage.getCurrent(), thingPage.getSize(), thingPage.getTotal());
        pageR.setCode(0);
        pageR.setCount(thingPage.getTotal());
        pageR.setSuccess(true);
        pageR.setMsg("成功");
        pageR.setData(thingPage.getRecords());

        return pageR;
    }


//    @PostMapping("/deleteGroup")
//    public R deletes(String index, int size, HttpSession session) {
//        User user = (User) session.getAttribute("user");
//        int userId = user.getUserId();
//        String[] split = index.split(",");
//        if (split.length == size) {
//            QueryWrapper<Thing> wrapper = new QueryWrapper<>();
//            wrapper.eq("user_id", userId);
//            List<Thing> list = thingService.list(wrapper);
//            List id = new ArrayList();
//            for (Thing thing : list) {
//                id.add(thing.getThingId());
//            }
//            thingService.removeByIds(id);
//        }
//        if (split.length < size) {
//
//        }
//
//    }

    /**
     * 批量删除每日的事
     *
     * @param data
     * @return
     */
    @PostMapping("/deletes")
    public R deletes(@RequestBody List<Thing> data) {
        {
            log.info("data size:[{}]", data.size());
            List<Integer> ids = new ArrayList<>();
            for (Thing datum : data) {
                ids.add(datum.getThingId());
            }
            boolean b = thingService.removeByIds(ids);
            if (b) {
                return R.success("删除成功");
            } else {
                return R.error("删除失败");
            }
        }


    }

    /**
     * 改变完成状态
     *
     * @param thingId
     * @param session
     * @return
     */
    @PostMapping("/change/{thingId}")
    public R change(@PathVariable int thingId, HttpSession session) {
        log.info("thingid:{}:", thingId);
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return R.error("请登录");
        }
        QueryWrapper<Thing> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getUserId());
        wrapper.eq("thing_id", thingId);
        Thing one = thingService.getOne(wrapper);
        if (one.getState() == ThingEnum.FINISH.getCode()) {
            one.setState(ThingEnum.NOT_FINISH.getCode());
            one.setCreateTime(new Date());
        } else {
            one.setState(ThingEnum.FINISH.getCode());
            one.setCreateTime(new Date());
        }

        boolean b = thingService.saveOrUpdate(one);
        return b ? R.success("改变成功") : R.error("改变失败");
    }

    @PostMapping("/list")
    public PageR list(@RequestParam int page, @RequestParam int limit, HttpSession session, String name) {
//        User user = (User) session.getAttribute("user");
        PageR pageR = new PageR();
//        pageR.setCode(1);
//        pageR.setCount(0L);
//        pageR.setSuccess(false);
//        pageR.setMsg("");


        User user = (User) session.getAttribute("user");
        if (user == null) {
            return pageR;
        }
        log.info("page:[{}],size:[{}]", page, limit);

        Page<Thing> thingPage = new Page<>(page, limit);
        thingService.pageListCondition(thingPage, user.getUserId(), name);
        log.info("pagegoods:[{}],size:[{}],total:[{}]", thingPage.getCurrent(), thingPage.getSize(), thingPage.getTotal());
        pageR.setCode(0);
        pageR.setCount(thingPage.getTotal());
        pageR.setSuccess(true);
        pageR.setMsg("成功");
        pageR.setData(thingPage.getRecords());


//        QueryWrapper<Thing> wrapper = new QueryWrapper<>();
//        wrapper.eq("user_id", user.getUserId());
//        wrapper.orderByAsc("state");
//        wrapper.orderByDesc("create_time");
//
//
//        List<Thing> list = thingService.list(wrapper);
//        pageR.setCode(0);
//        pageR.setCount(list.size());
//        pageR.setSuccess(true);
//        pageR.setMsg("成功");
//        pageR.setData(list);
        return pageR;
    }
}
